import os.path
import re
import requests
import HaoyunUse
from lxml import etree

class Spider:

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.session = requests.session()
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0"
        }
        self.auth_data = {}

    def _request(self, method, url, retry=5, timeout=5, **kwargs):
        """
        请求函数
        :param method: 请求方法 小写
        :param url: 请求链接
        :param retry: 请求重试次数 默认20
        :param timeout: 请求等待最大时间
        :param kwargs:
        :return:
        """
        if method in ["get", "post"]:
            # 请求重发
            for _ in range(retry + 1):
                try:
                    # print("发送%s请求 %s" % (method, url))
                    response = getattr(self.session, method)(url, timeout=timeout, **kwargs)
                    return response
                except Exception as e:
                    print(e)
        return None


    def login(self):
        response = self.session.post(
            url="http://www.medhw.cn/user/login.aspx",
            data={
                "__VIEWSTATE": "/wEPDwUKLTgzMDE2MDMxMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFBWxvZ2luDteqdEEBFmMTvORDTnn2T0jlSnDZ5LbliKq9nucQCRo=",
                "__VIEWSTATEGENERATOR": "C93BE1AE",
                "__EVENTVALIDATION": "/wEdAATWeB9juI3G7SUHiqS4MQnu1VXLCZniQEihPDabNrSt9Eb4Jgz7HnIzKj7/kLiIRTsrU8x5SglfzmEU2KqYFKCXfQ2HqXlueDjDRP+uXJ6vjl9n3fdWL2wnKHL+flgnwPA=",
                "name": self.username,
                "pass": self.password,
                "login.x": "64",
                "login.y": "22"
            },
            headers=self.headers
        )
        return response

    def get_data_auth(self, response):
        VIEWSTATEGENERATOR = etree.HTML(response.text).xpath("//input[@id='__VIEWSTATEGENERATOR']/@value")[0]
        EVENTVALIDATION = etree.HTML(response.text).xpath("//input[@id='__EVENTVALIDATION']/@value")[0]
        VIEWSTATE = etree.HTML(response.text).xpath("//input[@id='__VIEWSTATE']/@value")[0]
        print(VIEWSTATE)
        self.auth_data = {"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
                "__EVENTVALIDATION":EVENTVALIDATION,
                "__VIEWSTATE":VIEWSTATE}


    def find_list(self, start_date, end_date):
        infos = []
        response = self._request(method="get", url="http://www.medhw.cn/User/Query.aspx",
                                 headers=self.headers)
        self.get_data_auth(response)
        data = {
            "ctl00$ContentPlaceHolder1$dateStar": f"{start_date} 00:00:00",
            "ctl00$ContentPlaceHolder1$dateEnd": f"{end_date} 23:59:59",
            "ctl00$ContentPlaceHolder1$submit": "查询",
        }
        data.update(self.auth_data)
        response = self._request(method="post",url="http://www.medhw.cn/User/Query.aspx",
                                     headers=self.headers, data=data)
        element = etree.HTML(response.text)
        for tr in element.xpath("//tbody/tr"):
            name = tr.xpath("./td/text()")[2]
            detail = tr.xpath("./td/text()")[5]
            pdf_link = tr.xpath("./td/a/@onclick")
            code = re.findall("\(\'(.*?)\'\)", pdf_link[0])[0]
            pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9]')
            # 替换非目标字符为空
            cleaned_text = re.sub(pattern, '_', name + detail)
            # self.download(code, cleaned_text)
            infos.append({"code": code, "name": cleaned_text})

        while 1:
            if etree.HTML(response.text).xpath("//a[text()='下一页']/@href") and not etree.HTML(response.text).xpath("//a[text()='下一页'][@disabled='disabled']/@href"):
                data2 = {
                    "ctl00$ContentPlaceHolder1$dateStar": f"{start_date} 00:00:00",
                    "ctl00$ContentPlaceHolder1$dateEnd": f"{end_date} 23:59:59",
                    "__EVENTTARGET": "ctl00$ContentPlaceHolder1$Pager1", "__EVENTARGUMENT":str(re.findall("\'(\d+)\'",
                                                      etree.HTML(response.text).xpath("//a[text()='下一页']/@href")[0])[0])
                }
                print(data2["__EVENTARGUMENT"])

                self.get_data_auth(response)
                data2.update(self.auth_data)
                response = self._request(method="post", url="http://www.medhw.cn/User/Query.aspx",
                                         headers=self.headers, data=data2)
                element = etree.HTML(response.text)
                for tr in element.xpath("//tbody/tr"):
                    name = tr.xpath("./td/text()")[2]
                    detail = tr.xpath("./td/text()")[5]
                    pdf_link = tr.xpath("./td/a/@onclick")
                    code = re.findall("\(\'(.*?)\'\)", pdf_link[0])[0]
                    pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9]')
                    # 替换非目标字符为空
                    cleaned_text = re.sub(pattern, '_', name + detail)
                    # self.download(code, cleaned_text)
                    infos.append({"code":code, "name":cleaned_text})
            else:
                break
        return infos

    def download(self, code, name):
        url = f"http://www.medhw.cn/User/Report.aspx?ReportNum={code}"
        response = self.session.get(url=url, headers=self.headers)
        code = re.findall("var DEFAULT_URL = '\./file/(.*?)';", response.text)[0]
        response = self.session.get(url=f"http://www.medhw.cn/User/file/{code}")
        print(f"http://www.medhw.cn/User/file/{code}")
        while 1:
            if os.path.exists(f"pdfs/{name}.pdf"):
                name += "(1)"
            else:
                break
        with open(f"pdfs/{name}.pdf", "wb+") as f:
            f.write(response.content)


if __name__ == '__main__':
    sp = Spider(username="0094", password="191209")
    sp.login()
    result = sp.find_list("2025-03-01", "2025-03-31")
